package org.abettor.pushbox.activity2;

/**
 * 列表操作的抽象基类
 */
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.abettor.pushbox.config.Config;
import org.abettor.pushbox.download.ParaDownloadRetValue;
import org.abettor.pushbox.model.LastTimeIdInterface;
import org.abettor.pushbox.model.SelfMessage;
import org.abettor.pushbox.R;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

public abstract class AbstractListActivity extends ListActivity {
	private int isHasMore;// 判断是否还有更多的数据
	private boolean isLoading = false;// 判断当前的状态，是否处于加载状态
	private Handler mHandler = new Handler();
	private ProgressBar progressBar;// 进度条
	private Date lastAccessTime = null;// 用来存取最后一条记录的基准时间
	protected UserMapAdapter userMapAdapter;// 用户的监听器
	protected abstract boolean needDialog();//是否需要显示dialog
	protected abstract void alertMsg();//显示对话框
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		if(needDialog()){//需要显示对话框时
			SelfMessage self = Config.readSelfMessage(this);
			if (self == null) {
				super.onCreate(savedInstanceState);
				alertMsg();
				return;
			}
		}
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.abstract_list_activity);
		addFooterView(this.getListView());
		userMapAdapter = createAdapter();
		this.getListView().setAdapter(userMapAdapter);
		this.getListView().setOnScrollListener(new MyOnScrollListener());
	}
	//创建
	protected UserMapAdapter createAdapter(){
		return new UserMapAdapter(
				new LinkedList<LastTimeIdInterface>());
	}
	@Override
	protected void onStart(){
		if(needDialog()){
			SelfMessage self = Config.readSelfMessage(this);
			if(self==null){
				super.onStart();
				return;
			}
		}
		super.onStart();
		AbstractListActivity.this.loadList();
	}
	// 滚动条的监听器
	private class MyOnScrollListener implements OnScrollListener {
		private boolean linloading = false;
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// 把totalItemCount剔除掉，因为加入footer，所以剔除掉totalItemCount为1的时候
			if (totalItemCount == 1) {
				return;
			}
			if (firstVisibleItem + visibleItemCount >= totalItemCount
					&& isHasMore == ParaDownloadRetValue.HASMORE) {
				if (!linloading) {
					linloading = true;
					loadMap();// 加载数据
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							linloading = false;
						}
					}, 4000);
				}
				//loadMap();// 加载数据
			}
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
		}

		protected void loadMap() {
			loadList();// 获得答案列表的操作
		}
	}
	// 增加footer view
	private void addFooterView(ListView listView) {
		View localView = LayoutInflater.from(this).inflate(
				R.layout.net_user_map_list_footer, null);
		listView.addFooterView(localView);
	}
	// 显示加载网络地图错误的的对话狂
	private void loadNetMapFailure() {
		mHandler.post(new LoadFailureRunnable() {
			@Override
			public void loadMap() {
				loadList();
			}
		});
	}
	// 加载数据
	private void loadList() {
		// 已经加载时地图就不在加载
		if (isLoading) {
			return;
		}
		Thread thread = new Thread() {
			@Override
			public void run() {
				loadListOperation();// 加载答案列表的操作
			}
		};
		isLoading = true;
		showProgressBar();// 显示加载中的progressbar
		thread.start();
	}
	// 加载网络数据的操作
	private void loadListOperation() {
		lastAccessTime = userMapAdapter.getLastAccessTime();// 获得最近存取的时间
		String content = loadContentFromNet(lastAccessTime);
		dispearProgressBar();// 使加载框消失
		isLoading = false;
		// 读取内容为空，显示加载失败的对话框
		if (content == null) {
			loadNetMapFailure();// 显示加载失败的对话框
			return;
		}
		// 判断是否还有更多的数据
		isHasMore = isHasMoreData(content);
		// 解析数据内容失败，显示加载失败的对话框
		if (isHasMore == ParaDownloadRetValue.ERROR) {
			loadNetMapFailure();// 显示加载失败的对话框
			return;
		}
		// 解析数据的列表
		final List<LastTimeIdInterface> reList = paraData(content);
		if (reList == null) {
			loadNetMapFailure();// 显示加载失败的对话框
			return;
		}
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				userMapAdapter.addMapUserBean(reList);
				userMapAdapter.notifyDataSetChanged();
			}
		});
		// 显示用户的对话框
		showListMapView();
	}
	// show List View
	private void showListMapView() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				if (AbstractListActivity.this.getListView()
						.getVisibility() == View.GONE) {
					AbstractListActivity.this.getListView()
							.setVisibility(View.VISIBLE);
					TextView textView = (TextView) AbstractListActivity.this
							.findViewById(R.id.no_answer);
					textView.setVisibility(View.VISIBLE);
				}
			}
		});
	}
	// dispear progressBar
	private void dispearProgressBar() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				int state = AbstractListActivity.this.getListView()
						.getVisibility();
				if (state == View.GONE) {// 大对话框，消失的操作
					progressBar = (ProgressBar) AbstractListActivity.this
							.findViewById(R.id.progressBar1);
					progressBar.setVisibility(View.GONE);
				} else {// 小对话框的消失操作
					View view = AbstractListActivity.this
							.findViewById(R.id.footor);
					view.setVisibility(View.GONE);
				}
			}
		});
	}
	// 显示加载的对话框
	private void showProgressBar() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				TextView textView = (TextView) AbstractListActivity.this
						.findViewById(R.id.no_answer);
				textView.setVisibility(View.GONE);
				// 当列表框还没显示时显示大的加载框
				int state = AbstractListActivity.this.getListView()
						.getVisibility();
				if (state == View.GONE) {
					progressBar = (ProgressBar) AbstractListActivity.this
							.findViewById(R.id.progressBar1);
					progressBar.setVisibility(View.VISIBLE);
				} else {
					View view = AbstractListActivity.this.getListView()
							.findViewById(R.id.footor);
					view.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	/**
	 * 进行加载失败处理的类
	 * 
	 * @author jzh
	 * 
	 */
	private abstract class LoadFailureRunnable implements Runnable {
		@Override
		public void run() {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					AbstractListActivity.this);
			AlertDialog alert = builder.create();
			alert.setTitle(R.string.error);
			alert.setMessage(AbstractListActivity.this
					.getText(R.string.abstract_list_loaddata_failure));
			alert.setButton(DialogInterface.BUTTON_POSITIVE,
					AbstractListActivity.this.getText(R.string.netuser_retry),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 显示加载的对话标签
							showProgressBar();
							// 重新网络地图的操作
							loadMap();
						}
					});
			alert.setButton(DialogInterface.BUTTON_NEGATIVE,
					AbstractListActivity.this.getText(android.R.string.cancel),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			alert.show();
		}
		public abstract void loadMap();
	}

	protected class UserMapAdapter extends BaseAdapter {
		protected List<LastTimeIdInterface> resoveUserList;

		/**
		 * 获得最后一次更新时间
		 * 
		 * @return
		 */
		public Date getLastAccessTime() {
			if (resoveUserList == null || resoveUserList.isEmpty()) {
				return null;
			}
			int size = resoveUserList.size();
			LastTimeIdInterface bean = null;
			synchronized (resoveUserList) {
				bean = resoveUserList.get(size - 1);
			}
			return bean.getTime();
		}

		public void addMapUserBean(List<LastTimeIdInterface> toAdd) {
			if (toAdd == null) {
				return;
			}
			Date lastTime = getLastAccessTime();
			Iterator<LastTimeIdInterface> itr = toAdd.iterator();
			while (itr.hasNext()) {
				LastTimeIdInterface net = itr.next();
				if (lastTime == null || net.getTime().before(lastTime)) {
					resoveUserList.add(net);
				} else {
					resoveUserList.add(0, net);
				}
			}
		}

		public UserMapAdapter(List<LastTimeIdInterface> list) {
			this.resoveUserList = list;
		}

		@Override
		public int getCount() {
			synchronized (resoveUserList) {
				return resoveUserList.size();
			}
		}

		@Override
		public Object getItem(int position) {
			synchronized (resoveUserList) {
				return resoveUserList.get(position);
			}
		}

		@Override
		public long getItemId(int position) {
			synchronized (resoveUserList) {
				return resoveUserList.get(position).getId();
			}
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final LastTimeIdInterface item;
			synchronized (resoveUserList) {
				item = resoveUserList.get(position);
			}
			return layoutView(position, convertView, parent, item);
		}
	}

	/**
	 * 获得列表的view
	 * 
	 * @param position
	 * @param convertView
	 * @param parent
	 * @param bean
	 * @return
	 */
	protected abstract View layoutView(int position, View convertView,
			ViewGroup parent, LastTimeIdInterface bean);
	/**
	 * 从网络上加载数据的操作
	 * @param time
	 * @return
	 */
	protected abstract String loadContentFromNet(Date time);
	/**
	 * 判断是否有更多的数据
	 * @param content
	 * @return
	 */
	protected  abstract int isHasMoreData(String content);
	/**
	 * 解析数据生成的列表
	 * @param content
	 * @return
	 */
	protected abstract List<LastTimeIdInterface> paraData(String content);
}
